package com.softeem.iov.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;

@Component
public class QiniuOssUtils {

    //上传管理器
    @Autowired
    private UploadManager uploadManager;
    //桶管理器
    @Autowired
    private BucketManager bucketManager;
    //域名
    @Autowired
    private String domain;
    //存储桶名称
    @Autowired
    private String bucket;
    @Autowired
    private String token;

    /**
     * 文件上传
     * @param file
     * @param key
     * @return
     * @throws QiniuException
     */
    public String upload(File file, String key) throws IOException {
        return upload(Files.newInputStream(file.toPath()),key);
    }

    /**
     * 流上传
     * @param is
     * @param key
     * @return
     * @throws QiniuException
     */
    public String upload(InputStream is,String key) throws QiniuException {
        Response resp = uploadManager.put(is, key, token, null, null);
        DefaultPutRet dpr = new Gson().fromJson(resp.bodyString(), DefaultPutRet.class);
        key = dpr.key;
        return domain + key;
    }

    /**
     * 文件删除
     * @param key
     * @return
     */
    public boolean del(String key)  {
        try {
            bucketManager.delete(bucket, key);
            return true;
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }

}
